// pages/yq/submit.js

const util = require('../../utils/util.js');
const apiUrl = require('../../utils/apiUrl.js');
var http = require('../../utils/httpHelper.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    detail: {},
    winWidth: 0,
    winHeight: 0,
    collectUrl: "",
    collectUrlNew: "",
    articleTitle: "",
    latitude: 0,
    longitude: 0,
    position: "",
    videoSrc: "",
    fileUrl: "",
    contactPerson: "",
    contactPhone: "",
    loaddinghidden: true,
    formats: {},
    readOnly: false,
    keyboardHeight: 0,
    isIOS: false,
    showLoading: false,
    // 审核期临时关闭定位功能
    enableLocation: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const that = this
    var id = options.id;
    if (id) {
      that.setData({
        id: id
      })
      wx.setNavigationBarTitle({
        title: '编辑舆情',
      })
      that.loadData();
    }

    /**
     * 获取系统信息
     */
    wx.getSystemInfo({

      success: function(res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });

    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({
      isIOS
    })

    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)

    })

    // 审核期临时关闭定位：不获取定位
    if (this.data.enableLocation) {
      this.safeGetLocation();
    }
  },
  // 运行时检查定位接口可用性与授权
  checkLocationAvailability: function (needChoose, cb) {
    const canGet = !!wx.canIUse && wx.canIUse('getLocation');
    const canChoose = !!wx.canIUse && wx.canIUse('chooseLocation');
    if (!canGet || (needChoose && !canChoose)) {
      wx.showModal({
        title: '提示',
        content: '当前版本未开通定位/选点能力，请稍后重试或跳过位置填写',
        showCancel: false
      });
      typeof cb === 'function' && cb(false, { reason: 'api_unavailable' });
      return;
    }
    wx.getSetting({
      success: (res) => {
        const auth = res.authSetting && res.authSetting['scope.userLocation'];
        if (auth === false) {
          wx.showModal({
            title: '提示',
            content: '未授权位置信息，您可在设置中开启，或跳过位置填写',
            showCancel: false
          });
          cb && cb(false, { reason: 'denied' });
        } else {
          cb && cb(true);
        }
      },
      fail: () => {
        cb && cb(false, { reason: 'get_setting_fail' });
      }
    });
  },
  // 安全封装：获取定位
  safeGetLocation: function () {
    const that = this;
    this.checkLocationAvailability(false, function (ok) {
      if (!ok) return;
      wx.getLocation({
        type: 'wgs84',
        success: function(res) {
          var latitude = res.latitude
          var longitude = res.longitude
          wx.setStorageSync("latitude", latitude);
          wx.setStorageSync("longitude", longitude);
          that.setData({
            latitude: latitude,
            longitude: longitude
          });
        },
        fail: function(err) {
          console.log("getLocation fail:", err);
        }
      })
    });
  },

  chooseLocation: function() {
    var that = this;
    if (!this.data.enableLocation) {
      wx.showToast({ title: '本版本暂不提供位置功能', icon: 'none' });
      return;
    }
    var latitude = wx.getStorageSync("latitude");
    var longitude = wx.getStorageSync("longitude");
    this.checkLocationAvailability(true, function (ok) {
      if (!ok) return;
      wx.chooseLocation({
        latitude: latitude,
        longitude: longitude,
        success(res) {
          console.log(res);
          that.setData({
            latitude: res.latitude,
            longitude: res.longitude,
            position: res.address,
          });
        },
        fail(err) {
          console.log('chooseLocation fail:', err);
        }
      });
    });
  },

  loadData: function() {
    var that = this;
    var parameter = {};
    parameter['id'] = that.data.id;

    http.ApiGet(apiUrl.UrlYqDetail, parameter, function(res) {
      if (res.code == 1) {
        that.setData({
          loaddinghidden: true,
          articleTitle: res.data.title,
          detail: res.data,
          videoSrc: res.data.video,
          collectUrl: res.data.collect_url,
          collectUrlNew: res.data.collect_url,
          latitude: res.data.lat,
          longitude: res.data.lng,
          position: res.data.address,
          contactPerson: res.data.contact_person,
          contactPhone: res.data.contact_phone,
        });
      } else {
        wx.showModal({
          title: res.msg
        });
      }
    });
  },
  collectUrlInput: function (e) {
    this.setData({
      collectUrlNew: e.detail.value
    })
  },
  cjBtnTap: function () {
    var that = this;

    if (that.data.collectUrlNew.length==0){
      wx.showModal({
        title: '请输入采集网址',
      });
      return;
    }
    that.setData({
      loaddinghidden: false,
    });

    var parameter = {};
    parameter['url'] = that.data.collectUrlNew;

    http.ApiGet(apiUrl.UrlDoCacth, parameter, function (res) {
      var result = res.result;
      if (result.errorCode == 1) {
        that.setData({
          loaddinghidden: true,
          articleTitle: res.data.subject,
        });

        that.editorCtx.setContents({
          html: res.data.message,
          success: (res) => {
            console.log(res);
          },
          fail: (err) => {
            console.log(err);
          }
        });
      } else {
        wx.showModal({
          title: result.errorMessage
        });
      }
    });
  },
  formSubmit: function(e) {

    var that = this;

    var formData = e.detail.value;

    if (formData.title == "") {
      wx.showModal({
        title: '请填写标题',
      });
      return;
    }

    var collectUrl = that.data.collectUrl;
    if (collectUrl.length > 0) {
      formData["collect_url"] = collectUrl;
    }

    var collectUrlNew = that.data.collectUrlNew;
    if (collectUrlNew.length > 0) {
      formData["collect_url"] = collectUrlNew;
    }

    var videoSrc = that.data.videoSrc;
    if (videoSrc.length > 0) {
      formData["video"] = videoSrc;
    }

    formData["address"] = that.data.position;

    var longitude = that.data.longitude;
    if (longitude > 0) {
      formData["lng"] = longitude;
    }
    var latitude = that.data.latitude;
    if (latitude > 0) {
      formData["lat"] = latitude;
    }

    var contactPerson = that.data.contactPerson;
    if (contactPerson.length > 0) {
      formData["contact_person"] = contactPerson;
    }

    var contactPhone = that.data.contactPhone;
    if (contactPhone.length > 0) {
      formData["contact_phone"] = contactPhone;
    }

    that.editorCtx.getContents({
      success: (res) => {
        console.log(res);
        if (res.text.length > 0 && res.html != "<p><br></p>") {

          var content = res.html;

          var fileUrl = that.data.fileUrl;
          if (fileUrl.length > 0) {
            content += "<p><a href='" + fileUrl + "'>附件：" + fileUrl + "</a></p>";
          }
          formData["content"] = content;

          that.submitPost(formData);
        } else {
          wx.showModal({
            title: '请填写内容',
          });
          return;
        }
      },
      fail: (err) => {
        wx.showModal({
          title: '提交失败',
        });
        console.log(err);
      }
    });
  },
  submitPost(formData) {
    var that = this;

    console.log(formData);
    // return;

    wx.showToast({
      title: '正在提交',
      icon: 'loading',
      duration: 2000,
      mask: true,
    });

    var url = apiUrl.UrlYqSubmit;

    if (that.data.id > 0) {
      formData["id"] = that.data.id;
    }

    http.ApiPost(url, formData, function(res) {
      if (res.code == 1) {
        wx.showToast({
          title: '提交成功！',
          icon: 'success',
          duration: 2000
        });
        wx.navigateBack();
      } else {
        wx.showModal({
          title: res.msg
        });
      }
    });
  },
  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const {
      windowHeight,
      platform
    } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    this.setData({
      editorHeight,
      keyboardHeight
    })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const {
      statusBarHeight,
      platform
    } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function(res) {
      that.editorCtx = res.context;
      var detail = that.data.detail;
      if (detail.content) {
        that.editorCtx.setContents({
          html: detail.content,
          success: (res) => {
            console.log(res);
          },
          fail: (err) => {
            console.log(err);
          }
        });
      }
    }).exec()
  },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let {
      name,
      value
    } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)
  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({
      formats
    })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function() {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function(res) {
        console.log("clear success")
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  textIndent() {
    this.editorCtx.format('textIndent', '2em');
  },
  insertImage() {
    const that = this
    wx.chooseImage({
      count: 9,
      success: function(res) {
        for (let j = 0; j < res.tempFilePaths.length; ++j) {
          that.uploadImage(res.tempFilePaths[j])
        }
      }
    })
  },
  uploadImage: function(path) {
    var that = this
    that.showLoading();
    var postData = {};
    var user = wx.getStorageSync("user");
    if (user) {
      postData['appid'] = user.appid;
      postData['min_app'] = 1;
      wx.uploadFile({
        url: apiUrl.UrlUploadImg,
        filePath: path,
        name: 'file',
        formData: postData,
        success: function(res) {
          that.cancelLoading();
          var result = JSON.parse(res.data)
          // console.log(result);
          if (result.code == 1) {
            wx.hideToast();
            that.editorCtx.insertImage({
              src: result.data.url,
              width: '100%',
              success: function() {
                console.log('insert image success');
              }
            })
          } else {
            wx.showModal({
              title: result.msg
            });
          }
        },
        fail: function(err) {
          console.log(err);
          that.cancelLoading();
          wx.showModal({
            title: '上传出错！'
          });
        }
      })
    }
  },
  chooseVideo: function() {
    var that = this
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success: function(res) {
        console.log(res)
        that.uploadVideo(res.tempFilePath);
      }
    })
  },
  delVideo: function() {
    var that = this
    wx.showModal({
      title: '确定删除？',
      success: function(res) {
        if (res.confirm) {
          that.setData({
            videoSrc: ''
          })
        }
      }
    })
  },
  uploadVideo: function(path) {
    var that = this
    that.showLoading();
    var postData = {};
    var user = wx.getStorageSync("user");
    if (user) {
      postData['appid'] = user.appid;
      wx.uploadFile({
        url: apiUrl.UrlUploadVideo,
        filePath: path,
        name: 'file',
        formData: postData,
        success: function(res) {
          // console.log(res);
          that.cancelLoading();
          var result = JSON.parse(res.data)
          if (result.code == 1) {
            that.setData({
              videoSrc: result.data.url,
            });
          } else {
            wx.showModal({
              title: result.msg
            });
          }
        },
        fail: function(err) {
          console.log('err');
          that.cancelLoading();
          wx.showModal({
            title: '上传出错！'
          });
        }
      })
    }
  },
  showLoading: function() {
    this.setData({
      showLoading: true
    })
  },
  cancelLoading: function() {
    this.setData({
      showLoading: false
    })
  },
  fileBtnTap: function () {
    var that = this;
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success(res) {
        const tempFilePaths = res.tempFiles;
        console.log(tempFilePaths[0].path);
        that.uploadFile(tempFilePaths[0].path);
      }
    })
  },
  uploadFile: function (path) {
    var that = this
    that.showLoading();
    var postData = {};
    var user = wx.getStorageSync("user");
    if (user) {
      postData['appid'] = user.appid;
      postData['min_app'] = 1;
      wx.uploadFile({
        url: apiUrl.UrlUpload,
        filePath: path,
        name: 'file',
        formData: postData,
        success: function (res) {
          that.cancelLoading();
          var result = JSON.parse(res.data)
          console.log(result);
          if (result.code == 1) {
            wx.hideToast();

            var fileUrl = result.data.url;

            that.setData({
              fileUrl: fileUrl
            });

          } else {
            wx.showModal({
              title: result.msg
            });
          }
        },
        fail: function (err) {
          console.log(err);
          that.cancelLoading();
          wx.showModal({
            title: '上传出错！'
          });
        }
      })
    }
  },
})